<?php 
define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
require(ROOT_PATH . 'includes/lib_order.php');

/* 载入语言文件 */
require_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/user.php');
require_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/shopping_flow.php');

assign_template();
assign_dynamic('flow');
$position = assign_ur_here(0, $_LANG['shopping_flow']);
$smarty->assign('page_title',       $position['title']);    // 页面标题
$smarty->assign('ur_here',          $position['ur_here']);  // 当前位置



$smarty->assign('lang',             $_LANG);
$smarty->assign('show_marketprice', $_CFG['show_marketprice']);
$smarty->assign('data_dir',    DATA_DIR);       // 数据目录

$smarty->assign('step',            $_REQUEST['step']);


if($_REQUEST['step'] == 'done') 
{
    include_once('includes/lib_clips.php');
    include_once('includes/lib_payment.php');
    //重复提交判断
    if(!$_SESSION['buy_car'] ) {
       echo"<SCRIPT LANGUAGE='javascript'>alert('请不要重复提交');history.go(-1);</SCRIPT>";exit;
    }
    //$smarty->assign('buy_car',            $_SESSION['buy_car']);
      
    $goods_id =  empty($_POST['goods_id']) ? 0  :   intval($_POST['goods_id']) ;

    $jiage = intval($_POST['jiage']);
    $taoshu = empty($_POST['number']) ? 1  :   intval($_POST['number']) ;
    if (!$goods_id  ) { exit('没有选择对应的产品');}
    if (intval($goods_id>0))
    {
        $goodsArr = $GLOBALS['db']->getRow("select goods_id,cat_id,goods_sn,goods_name,goods_number,shop_price,market_price,is_real,extension_code from ".$GLOBALS['ecs']->table('goods')." where goods_id='$goods_id'");
        $jiage2 = intval($goodsArr['shop_price']); //总价=套数*单价
        if ($jiage2 != $jiage) {exit('价格错误');}
    }

	/*
     * 保存收货人信息
     */
    $consignee = array(
        
        'consignee'     => empty($_POST['name'])  ? '匿名' :   compile_str(trim($_POST['name'])),

        'email'         => empty($_POST['email'])      ? '' :   compile_str($_POST['email']),
      	'qq'           => empty($_POST['qq'])        ? '' :   compile_str(make_semiangle(trim($_POST['qq']))),
        'tel'           => empty($_POST['tel'])        ? '' :   compile_str(make_semiangle(trim($_POST['tel']))),
        'mobile'        => empty($_POST['mobile'])     ? '' :   compile_str(make_semiangle(trim($_POST['mobile']))),
        'sign_building' => empty($_POST['sign_building']) ? '' :compile_str($_POST['sign_building']),
        'best_time'     => empty($_POST['best_time'])  ? '' :   compile_str($_POST['best_time']),
    );
    $consignee = stripslashes_deep($consignee);
    if (empty($consignee['mobile'])) {
    	echo"<SCRIPT LANGUAGE='javascript'>alert('请输入完整信息后再提交！');history.go(-1);</SCRIPT>";exit;
    }
    $_SESSION['flow_consignee'] = $consignee;
    $_POST['how_oos'] = isset($_POST['how_oos']) ? intval($_POST['how_oos']) : 0;
    $_POST['postscript'] = isset($_POST['postscript']) ? compile_str($_POST['postscript']) : ''; //订单留言

    $order = array(
        'shipping_id'     => '-1', //自动发货
        'pay_id'          => isset($_POST['payment']) ? intval($_POST['payment']) : 1, //支付方式 1为支付宝 2为货到付款 3银行转账 4、网银支付
        'pack_id'         => isset($_POST['pack']) ? intval($_POST['pack']) : 0,
        'card_id'         => isset($_POST['card']) ? intval($_POST['card']) : 0,
        'card_message'    => trim($_POST['card_message']),
        'surplus'         => isset($_POST['surplus']) ? floatval($_POST['surplus']) : 0.00,
        'integral'        => isset($_POST['integral']) ? intval($_POST['integral']) : 0,
        'bonus_id'        => isset($_POST['bonus']) ? intval($_POST['bonus']) : 0,
        'need_inv'        => empty($_POST['need_inv']) ? 0 : 1,
        'inv_type'        => $_POST['inv_type'],
        'inv_payee'       => trim($_POST['inv_payee']),
        'inv_content'     => $_POST['inv_content'],
        'postscript'      => trim($_POST['postscript']),
        'how_oos'         => isset($_LANG['oos'][$_POST['how_oos']]) ? addslashes($_LANG['oos'][$_POST['how_oos']]) : '',
        'need_insure'     => isset($_POST['need_insure']) ? intval($_POST['need_insure']) : 0,
        'user_id'         => $_SESSION['user_id'],
        'add_time'        => gmtime(),
        'order_status'    => OS_UNCONFIRMED,
        'shipping_status' => SS_UNSHIPPED,
        'pay_status'      => PS_UNPAYED,
        'agency_id'       => get_agency_by_regions(array($consignee['country'], $consignee['province'], $consignee['city'], $consignee['district']))
        );
    $order['extension_code'] = '';
    $order['extension_id'] = 0;
    $order['surplus']  = 0;
    $order['integral'] = 0;

     /* 收货人信息 */
    foreach ($consignee as $key => $value)
    {
        $order[$key] = addslashes($value);
    }
    $order['bonus']        = 0;
    $order['goods_amount']  = $jiage;
    $order['discount']     = $total['discount'];
    $order['surplus']      = '';
    $order['tax']          = '0';


	/* 配送方式 */
    if ($order['shipping_id'] > 0)
    {
        $shipping = shipping_info($order['shipping_id']);
        $order['shipping_name'] = addslashes($shipping['shipping_name']);
    }
    $order['shipping_fee'] = $total['shipping_fee'];
    $order['insure_fee']   = $total['shipping_insure'];

	/* 支付方式 */
	if ($order['pay_id'] > 0)
    {
        $payment = payment_info($order['pay_id']);
        $order['pay_name'] = addslashes($payment['pay_name']);
    }
  
    $order['pack_fee'] = '0';
    $order['card_fee']      ='0';
    $order['order_amount']  = number_format($jiage, 2, '.', '');
    $order['integral_money']   ='0';
    $order['integral']   ='0';
    $order['from_ad'] = '0';
    $order['referer'] = '本站';
    $order['parent_id'] = 0 ;
    $order['ip'] = real_ip(); //获取客服端ip
    
    /* 插入订单表 */
    $error_no = 0;
    do
    {
        $order['order_sn'] = get_order_sn(); //获取新订单号
        // print_r($order);exit;
        $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('order_info'), $order, 'INSERT');

        $error_no = $GLOBALS['db']->errno();

        if ($error_no > 0 && $error_no != 1062)
        {
            die($GLOBALS['db']->errorMsg());
        }
    }
    while ($error_no == 1062); //如果是订单号重复则重新提交数据
    $new_order_id = $db->insert_id();
    $order['order_id'] = $new_order_id;


    /* 插入订单商品 */
    $sql = "INSERT INTO " . $ecs->table('order_goods') . "( " .
                "order_id, goods_id, goods_name, goods_sn, product_id, goods_number, market_price, ".
                "goods_price, goods_attr, is_real, extension_code, parent_id, is_gift, goods_attr_id) VALUES ( ".
                " '".$new_order_id."',  '".$goodsArr['goods_id']."', '".$goodsArr['goods_name']."', '".$goodsArr['goods_sn']."', '0' , '".$taoshu."' , '".$goodsArr['market_price']."' , '".$goodsArr['shop_price']."', '' , '".$goodsArr['is_real']."', '".$goodsArr['extension_code']."', '0','0',  '')";
           /* " SELECT '$new_order_id', goods_id, goods_name, goods_sn, product_id, goods_number, market_price, ".
                "goods_price, goods_attr, is_real, extension_code, parent_id, is_gift, goods_attr_id".
            " FROM " .$ecs->table('cart') .
            " WHERE session_id = '".SESS_ID."' AND rec_type = '$flow_type'";*/
    $db->query($sql);
    /* 如果使用库存，且下订单时减库存，则减少库存 */
    if ($_CFG['use_storage'] == '1' && $_CFG['stock_dec_time'] == SDT_PLACE)
    {
        change_order_goods_storage($order['order_id'], true, SDT_PLACE);
    }

    clear_all_files();
    /* 插入支付日志 */
    $order['log_id'] = insert_pay_log($new_order_id, $order['order_amount'], PAY_ORDER);
    /* 取得支付信息，生成支付代码 */
    if ($order['order_amount'] > 0)
    {
        $payment = payment_info($order['pay_id']);

        include_once('includes/modules/payment/' . $payment['pay_code'] . '.php');

        $pay_obj    = new $payment['pay_code'];

        $pay_online = $pay_obj->get_code($order, unserialize_config($payment['pay_config']), 1);

        $order['pay_desc'] = $payment['pay_desc'];

        $smarty->assign('pay_online', $pay_online);

        header("Location: $pay_online"); 
		exit;
    }
    if(!empty($order['shipping_name']))
    {
        $order['shipping_name']=trim(stripcslashes($order['shipping_name']));
    }

    /* 订单信息 */
   /* $smarty->assign('order',      $order);
    $smarty->assign('total',      $total);
    $smarty->assign('goods_list', $cart_goods);
    $smarty->assign('order_submit_back', sprintf($_LANG['order_submit_back'], $_LANG['back_home'], $_LANG['goto_user_center'])); // 返回提示
*/
    unset($_SESSION['buy_car']);



	
}elseif($_REQUEST['step'] == 'pay') {
	/* 包含加密解密函数所在文件 */
    include_once(ROOT_PATH . 'includes/lib_code.php');
$sql = "SELECT card_id, card_sn, card_password, end_date, crc32 FROM ".$GLOBALS['ecs']->table('virtual_card')."" ;
     $arr = $GLOBALS['db']->getAll($sql);
     foreach ($arr as $virtual_card)
     {
        $card_info = array();

        /* 卡号和密码解密 */
        if ($virtual_card['crc32'] == 0 || $virtual_card['crc32'] == crc32(AUTH_KEY))
        {
            $card_info['card_sn'] = decrypt($virtual_card['card_sn']);
            $card_info['card_password'] = decrypt($virtual_card['card_password']);
        }
        elseif ($virtual_card['crc32'] == crc32(OLD_AUTH_KEY))
        {
            $card_info['card_sn'] = decrypt($virtual_card['card_sn'], OLD_AUTH_KEY);
            $card_info['card_password'] = decrypt($virtual_card['card_password'], OLD_AUTH_KEY);
        }
        else
        {
            $msg .= 'error key';

            return false;
        }
        $card_info['end_date'] = date($GLOBALS['_CFG']['date_format'], $virtual_card['end_date']);
        $card_ids[] = $virtual_card['card_id'];
        $cards[] = $card_info;
     }
     if ($cards) {
            foreach ($cards as $key => $value) {
                $jhm .= "激活码:".$value['card_password'].',';
            }
            echo $jhm;
        }

}

 ?>